using Auth.Infrastructure.Repositories;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using BasicData.Infrastructure.Repositories;
using Consul;
using Hangfire;
using Microsoft.Extensions.DependencyInjection;
using NLog.Web;
using Quartz;
using SqlSugar;
using StackExchange.Redis;
using Warehouse.Api;
using Warehouse.Application;
using Warehouse.Application.Services;
using Warehouse.Application.Services.Libraryrecord;
using Warehouse.Domain.Entities;
using Warehouse.Infrastructure.Repositories;
using Yitter.IdGenerator;


var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(o =>
{
    var a = Path.Combine(AppContext.BaseDirectory, "Warehouse.Api.xml");
    o.IncludeXmlComments(a,true);
});

builder.Services.AddControllers();
// SqlSugar 注册
//builder.Services.AddScoped<ISqlSugarClient>(sp =>
//    new SqlSugarClient(new ConnectionConfig
//    {
//        ConnectionString = builder.Configuration.GetConnectionString("Oracle"),
//        DbType = DbType.Oracle,
//        IsAutoCloseConnection = true
//    }));
builder.Services.AddScoped<ISqlSugarClient>(sp =>
    new SqlSugarClient(new ConnectionConfig
    {
        ConnectionString = builder.Configuration.GetConnectionString("conn"),
        DbType = DbType.MySql,
        IsAutoCloseConnection = true,
        InitKeyType = InitKeyType.Attribute,
        MoreSettings=new ConnMoreSettings
        {
            IsAutoRemoveDataCache = true,
            IsAutoDeleteQueryFilter = true

        }
    }));

// 仓储与服务注册

builder.Services.AddScoped(typeof(IWarehouseModelRepository<>), typeof(WarehouseModelRepository<>));
builder.Services.AddScoped(typeof(IAuthRepository<>), typeof(AuthRepository<>));

// 服务扩展autofac
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory(x => x.RegisterModule(new AutoFacing())));
builder.Services.AddAutofac();
builder.Services.AddScoped(typeof(IBasicModelRepository<>), typeof(BasicModelRepository<>));

builder.Services.AddSingleton<IConsulClient, ConsulClient>(p => new ConsulClient(cfg =>
{
    cfg.Address = new Uri("http://120.26.197.100:8500");
}));

// 配置Quartz定时任务
builder.Services.AddQuartz(q =>
{
    // 创建Redis缓存刷新任务
    var jobKey = new JobKey("RefreshRedisCacheJob");

    q.AddJob<RedisCacheRefreshJob>(opts => opts.WithIdentity(jobKey));

    // 创建触发器，每天凌晨0:05执行
    q.AddTrigger(opts => opts
        .ForJob(jobKey)
        .WithIdentity("RefreshRedisCacheTrigger")
        .WithCronSchedule("0 5 0 * * ?")); // 每天00:05执行
});



//注入AutoMapper
builder.Services.AddAutoMapper(typeof(Mappering));
//雪花id注入
YitIdHelper.SetIdGenerator(new IdGeneratorOptions());
//Redis注入
builder.Services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect("120.26.197.100:6379"));

builder.Services.AddQuartzHostedService();


builder.Host.UseNLog();

var app = builder.Build();
app.UseCors(p=>p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.MapControllers();

app.MapGet("/health", () => Results.Ok("Ok"));



var consulClient = app.Services.GetRequiredService<IConsulClient>();
var registration = new AgentServiceRegistration
{
    ID = $"Warehouse-{Guid.NewGuid()}",
    Name = "Warehouse",
    Address = "120.26.197.100",
    Port = 8083,// 请根据实际端口调整
    //Address = "localhost",
    //Port = 7212,// 请根据实际端口调整
    Check = new AgentServiceCheck
    {
        HTTP = $"http://120.26.197.100:8083/health",
        //HTTP = $"http://localhost:7212/health",
        // 设置时间间隔为10秒，用于控制某些操作或检查的频率
        Interval = TimeSpan.FromSeconds(5),
        // 设置超时时间为5秒，用于防止某些操作无休止地等待下去
        Timeout = TimeSpan.FromSeconds(5),
        DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1) // 可选：健康检查失败多久后自动移除
    }
};
consulClient.Agent.ServiceRegister(registration).Wait();

var db = app.Services.GetRequiredService<ISqlSugarClient>();
db.CodeFirst.InitTables(typeof(ExternallabelModel));
db.CodeFirst.InitTables(typeof(StorageLocationModel));
db.CodeFirst.InitTables(typeof(StorageModel));
db.CodeFirst.InitTables(typeof(SuppliedMaterialsModel));
db.CodeFirst.InitTables(typeof(WareHouseModel));
db.CodeFirst.InitTables(typeof(MoIdModel));
db.CodeFirst.InitTables(typeof(LibraryrecordModel));
db.CodeFirst.InitTables(typeof(SpringWaterModel));
db.CodeFirst.InitTables(typeof(WideTableModel));

app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
